package com.albert.pjsua2;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class NetworkUtils {

    private BroadcastReceiver receiver;
    private IntentFilter intentFilter;

    private static NetworkUtils instance = new NetworkUtils();
    private NetworkUtils() {
    }

    public static NetworkUtils getInstance() {
        return instance;
    }
    private class MyBroadcastReceiver extends BroadcastReceiver {
        private String conn_name = "";

        @Override
        public void onReceive(Context context, Intent intent) {
            if (isNetworkChange(context)) SipManager.getInstance().notifyChangeNetwork();
        }

        private boolean isNetworkChange(Context context) {
            boolean network_changed = false;
            ConnectivityManager connectivity_mgr = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));

            NetworkInfo net_info = connectivity_mgr.getActiveNetworkInfo();
            if (net_info != null && net_info.isConnectedOrConnecting() && !conn_name.equalsIgnoreCase("")) {
                String new_con = net_info.getExtraInfo();
                if (new_con != null && !new_con.equalsIgnoreCase(conn_name)) network_changed = true;

                conn_name = (new_con == null) ? "" : new_con;
            } else {
                if (conn_name.equalsIgnoreCase("")) conn_name = net_info.getExtraInfo();
            }
            return network_changed;
        }
    }
    public void registerNetworkReceiver(Context context) {
        receiver = new MyBroadcastReceiver();
        intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        context.registerReceiver(receiver, intentFilter);
    }

    public void unregisterNetworkReceiver(Context context) {
        if (receiver != null) {
            context.unregisterReceiver(receiver);
        }
    }
}